<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\services\order;


use app\dao\order\StoreOrderDao;
use app\model\v1\gift\GiftCard;
use app\services\activity\lottery\LuckLotteryServices;
use app\services\BaseServices;
use app\services\pay\IntegralPayServices;
use app\services\pay\PayServices;
use app\services\product\product\StoreProductServices;
use app\services\user\UserBillServices;
use app\services\user\UserServices;
use crmeb\traits\ServicesTrait;
use think\exception\ValidateException;
use think\facade\Db;

/**
 * Class StoreOrderSuccessServices
 * @package app\services\order
 * @mixin StoreOrderDao
 */
class StoreOrderSuccessServices extends BaseServices
{
    use ServicesTrait;

    /**
     *
     * StoreOrderSuccessServices constructor.
     * @param StoreOrderDao $dao
     */
    public function __construct(StoreOrderDao $dao)
    {
        $this->dao = $dao;
    }

    /**
     * 0元支付
     * @param array $orderInfo
     * @param int $uid
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function zeroYuanPayment(array $orderInfo, int $uid, string $payType = PayServices::YUE_PAY)
    {
		$id = $orderInfo['id'] ?? 0;
		if (!$orderInfo || !$id) {
			throw new ValidateException('订单不存在!');
		}
		//更新订单信息
		$orderInfo = $this->dao->get($id);
		if (!$orderInfo) {
			throw new ValidateException('订单不存在');
		}
		$orderInfo = $orderInfo->toArray();
		if ($orderInfo['paid']) {
            throw new ValidateException('该订单已支付!');
        }
        return $this->paySuccess($orderInfo, $payType);//余额支付成功
    }

    /**
     * 支付成功
     * @param array $orderInfo
     * @param string $paytype
     * @return bool
     */
    public function paySuccess(array $orderInfo, string $paytype = PayServices::WEIXIN_PAY, array $other = [])
    {
        $updata = ['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time()];
        if ($other && isset($other['trade_no'])) {
            $updata['trade_no'] = $other['trade_no'];
        }
        $res1 = $this->dao->update($orderInfo['id'], $updata);
		$orderInfo['trade_no'] = $other['trade_no'] ?? '';
        $orderInfo['pay_time'] = time();
        $orderInfo['pay_type'] = $paytype;
        //缓存抽奖次数 除过线下支付 抽奖中奖订单
		if (isset($orderInfo['pay_type']) && $orderInfo['pay_type'] != 'offline' && isset($orderInfo['type']) && $orderInfo['type'] != 8) {
            /** @var LuckLotteryServices $luckLotteryServices */
            $luckLotteryServices = app()->make(LuckLotteryServices::class);
            $luckLotteryServices->setCacheLotteryNum((int)$orderInfo['uid'], 'order');
        }
		$userInfo = app()->make(UserServices::class)->get($orderInfo['uid']);
		if ($orderInfo['pay_integral']) {//需要支付积分
			/** @var IntegralPayServices $integralPayServices */
			$integralPayServices = app()->make(IntegralPayServices::class);
			$integralPayServices->integralOrderPay((int)$userInfo['uid'], $orderInfo, $userInfo->toArray());
		}
        if ($orderInfo['set_type']==1&&$orderInfo['product_type']==0){
            $user_kt_list = Db::name('water_user_kt_list')->where ('uid',$orderInfo['uid'])->whereNull('order_id')->find ();
            if ($user_kt_list){
                DB::name('water_user_kt_list')
                    ->where('uid',$orderInfo['uid'])
                    ->update(['order_id'=>$orderInfo['order_id']]);
            }
        }
		if ($orderInfo['product_type']!=6) {
			/** @var UserServices $userServices */
			$userServices = app()->make(UserServices::class);
			$userInfo = $userServices->get((int)$orderInfo['uid']);
			$order = $this->dao->getUserOrderDetail($orderInfo['order_id'], $orderInfo['uid']);
			/** @var StoreOrderTakeServices $StoreOrderTakeServices */
			$StoreOrderTakeServices = app()->make(StoreOrderTakeServices::class);
            $StoreOrderTakeServices->gainUserIntegral2($order,$userInfo,'');

//            if ($orderInfo['pay_type']!='yue'){
//            }

		}
		if ($orderInfo['type']==32){
			if ($orderInfo['integration_get']>0){

				/** @var UserBillServices $userBillServices */
				$userBillServices = app()->make(UserBillServices::class);
				$res3 = false != $userBillServices->income('integration_get_integral', $order['uid'], (int)$orderInfo['integration_get'], (int)$userInfo['integral'], $order['id']);
				$integral = $userInfo['integral'] + $orderInfo['integration_get'];
				$userInfo->integral = $integral;
				$res1 = false != $userInfo->save();
			}
		}
	    //_________________________________________  水站新定义的逻辑  ____________________________________________


        if($orderInfo['product_type']==5){
            $res1 = $this->dao->update($orderInfo['id'], ['status'=>2]);
        }
	    //添加水票记录
	    if ($orderInfo['product_type']==5||$orderInfo['type']==11){
		    $wate_ticket['nums']=0;
		    $wate_ticket['order_sn']=$orderInfo['order_id'];
		    $wate_ticket['user_id']=$orderInfo['uid'];
		    $wate_ticket['type']=1;
		    /** @var StoreOrderCartInfoServices $StoreOrderCartInfoServices */
		    $StoreOrderCartInfoServices =app()->make(StoreOrderCartInfoServices::class);
		    /** @var StoreProductServices $StoreProductServices */
		    $integralPayServices = app()->make(StoreProductServices::class);
		    $order_cart_info =  Db::name('store_order_cart_info')->where ('oid',$orderInfo['id'])->select ();

		    foreach ($order_cart_info as $v){
                $cart_info = json_decode($v['cart_info'], true);

                $water_ticket = Db::name('water_ticket')->where ('user_id',$orderInfo['uid'])->where ('goods_id',$cart_info['productInfo']['brand_id'])->order ('id','desc')->find ();

			    $num=0;
			    if ($water_ticket){
				    $num = $water_ticket['num']+$v['write_times'];
			    }else{
				    $num += $v['write_times'];
			    }
			    $wate_ticket['nums']=  $v['write_times'];
			    $wate_ticket['goods_id']=$cart_info['productInfo']['brand_id'];
			    $wate_ticket['num']= $num;
			    $wate_ticket['createtime']=date ('Y-m-d H:i:s');
			    $wate_ticket['updatetime']=date ('Y-m-d H:i:s');
			    $goods=$integralPayServices->get ($cart_info['product_id']);
			    $wate_ticket['remark']='购买'.'-'.$goods['store_name'].$wate_ticket['nums'].'张';


                if (strpos($goods['store_name'],'*')){
                    $goods['store_name'] = strstr ($goods['store_name'],'*',true);
                }
			    $wate_ticket['goods_name']=$goods['store_name'];
			    $wate_ticket['image']=$goods['image'];
			    Db::name('water_ticket')->insert ($wate_ticket);
			    $res1 = $this->dao->update($orderInfo['id'], ['status' => 3]);
				if ($goods['give_num']>0){
                    $goods['give_num']  = $goods['give_num']*$v['cart_num'];
					$water_ticket = Db::name('water_ticket')->where ('user_id',$orderInfo['uid'])->where ('goods_id','0')->order ('id','desc')->find ();
                    $give_num=0;
					if ($water_ticket){
						$give_num = $water_ticket['num']+$goods['give_num'];
					}else{
                        $give_num += $goods['give_num'];
					}
					$wate_ticket['nums']=  $goods['give_num'];
					$wate_ticket['goods_id']='0';
					$wate_ticket['num']= $give_num;
					$wate_ticket['createtime']=date ('Y-m-d H:i:s');
					$wate_ticket['updatetime']=date ('Y-m-d H:i:s');
					$wate_ticket['remark']='赠送'.'-百街立方水票'.$goods['give_num'].'个';
					$wate_ticket['goods_name']=$goods['give_name'];
                    $img =json_decode($goods['give_img'],true);
					$wate_ticket['image']= $img[0];
					Db::name('water_ticket')->insert ($wate_ticket);
				}
		    }
	    }
	    //空桶押金
	    if ($orderInfo['product_type']==6){
		    $water_user=Db::name('water_user')->where ('uid',$orderInfo['uid'])->find ();
//		    /** @var StoreOrderCartInfoServices $StoreOrderCartInfoServices */
//		    $StoreOrderCartInfoServices =app()->make(StoreOrderCartInfoServices::class);
		    foreach ($orderInfo['cart_id'] as $v){
			    $data=Db::name('store_order_cart_info')->where ('oid',$orderInfo['id'])->select();
		    }
		    $write_times=0;
		    foreach ($data as $v){
			    $write_times=$v['write_times'];
			    if (!$write_times){
				    throw new ValidateException('空桶押金数量不能小于0桶');
			    }
			    $this->dao->update($orderInfo['id'], ['stauts'=>3]);
			    if ($water_user){
				    Db::name('water_user')->where ('uid',$orderInfo['uid'])->inc('kt_pledge',$write_times)->update ();
			    }else{
				    Db::name('water_user')->where ('uid',$orderInfo['uid'])->insert(['kt_pledge'=>$write_times,'uid'=>$orderInfo['uid']]);
			    }

		    }
	    }
        //订单支付成功事件
        event('order.pay', [$orderInfo, $userInfo]);
        $res = $res1;
        return false !== $res;
    }

}
